const axios = require('axios');

class RuleEngine {
    constructor() {
        this.rules = [];
        this.variables = {};
    }

    // 添加规则
    addRule(rule) {
        this.rules.push({
            id: Date.now() + Math.random().toString(36).substr(2, 9),
            ...rule,
            active: rule.active !== false // 默认激活
        });
        console.log(`📋 规则已添加: ${rule.name}`);
    }

    // 更新变量值
    updateVariable(name, value) {
        this.variables[name] = value;
        console.log(`🔄 变量更新: ${name} = ${value}`);
        // 检查是否触发规则
        this.evaluateRules();
    }

    // 批量更新变量
    updateVariables(variables) {
        Object.assign(this.variables, variables);
        console.log(`🔄 批量变量更新:`, variables);
        // 检查是否触发规则
        this.evaluateRules();
    }

    // 获取变量值
    getVariable(name) {
        return this.variables[name];
    }

    // 获取所有变量
    getAllVariables() {
        return { ...this.variables };
    }

    // 评估所有规则
    evaluateRules() {
        console.log('🔍 评估规则...');
        const triggeredRules = [];
        
        for (const rule of this.rules) {
            if (!rule.active) continue;
            
            try {
                const conditionResult = this.evaluateCondition(rule.condition);
                if (conditionResult) {
                    console.log(`✅ 规则触发: ${rule.name}`);
                    triggeredRules.push(rule);
                    // 执行动作
                    this.executeActions(rule.actions);
                }
            } catch (error) {
                console.error(`❌ 规则评估失败 ${rule.name}:`, error);
            }
        }
        
        return triggeredRules;
    }

    // 评估条件
    evaluateCondition(condition) {
        if (!condition) return false;
        
        // 简单条件评估
        if (condition.variable && condition.operator && condition.value !== undefined) {
            const varValue = this.variables[condition.variable];
            if (varValue === undefined) return false;
            
            switch (condition.operator) {
                case '=':
                case '==':
                    return varValue == condition.value;
                case '===':
                    return varValue === condition.value;
                case '!=':
                    return varValue != condition.value;
                case '!==':
                    return varValue !== condition.value;
                case '>':
                    return varValue > condition.value;
                case '>=':
                    return varValue >= condition.value;
                case '<':
                    return varValue < condition.value;
                case '<=':
                    return varValue <= condition.value;
                case 'includes':
                    return String(varValue).includes(String(condition.value));
                default:
                    return false;
            }
        }
        
        // 复合条件评估 (AND)
        if (condition.and) {
            return condition.and.every(subCondition => this.evaluateCondition(subCondition));
        }
        
        // 复合条件评估 (OR)
        if (condition.or) {
            return condition.or.some(subCondition => this.evaluateCondition(subCondition));
        }
        
        return false;
    }

    // 执行动作
    async executeActions(actions) {
        if (!actions || !Array.isArray(actions)) return;
        
        for (const action of actions) {
            try {
                switch (action.type) {
                    case 'plc-write':
                        await this.executePLCWrite(action);
                        break;
                    case 'db-write':
                        await this.executeDBWrite(action);
                        break;
                    case 'notification':
                        await this.executeNotification(action);
                        break;
                    case 'log':
                        await this.executeLog(action);
                        break;
                    default:
                        console.warn(`⚠️ 未知动作类型: ${action.type}`);
                }
            } catch (error) {
                console.error(`❌ 动作执行失败:`, error);
            }
        }
    }

    // 执行PLC写入动作 - 通过队列服务
    async executePLCWrite(action) {
        console.log(`📤 执行PLC写入动作:`, action);
        
        try {
            // 通过队列服务执行PLC写入操作
            const response = await axios.post('http://localhost:3003/api/queue/task', {
                task: {
                    type: 'plc-write',
                    variable: action.variable,
                    value: action.value
                }
            });
            
            console.log(`✅ PLC写入任务已提交到队列:`, response.data);
            return response.data;
        } catch (error) {
            console.error(`❌ PLC写入任务提交失败:`, error.message);
            throw new Error(`PLC写入任务提交失败: ${error.message}`);
        }
    }

    // 执行数据库写入动作 - 通过队列服务
    async executeDBWrite(action) {
        console.log(`💾 执行数据库写入动作:`, action);
        
        try {
            // 通过队列服务执行数据库写入操作
            const response = await axios.post('http://localhost:3003/api/queue/task', {
                task: {
                    type: 'db-write',
                    data: action.data
                }
            });
            
            console.log(`✅ 数据库写入任务已提交到队列:`, response.data);
            return response.data;
        } catch (error) {
            console.error(`❌ 数据库写入任务提交失败:`, error.message);
            throw new Error(`数据库写入任务提交失败: ${error.message}`);
        }
    }

    // 执行通知动作
    async executeNotification(action) {
        console.log(`🔔 执行通知动作:`, action);
        // 这里可以发送邮件、短信或其他通知
        console.log(`✅ 通知已发送: ${action.message}`);
    }

    // 执行日志动作
    async executeLog(action) {
        console.log(`📝 执行日志动作:`, action);
        // 这里可以写入日志文件或数据库
        console.log(`✅ 日志记录: ${action.message}`);
    }

    // 获取所有规则
    getRules() {
        return [...this.rules];
    }

    // 激活规则
    activateRule(ruleId) {
        const rule = this.rules.find(r => r.id === ruleId);
        if (rule) {
            rule.active = true;
            console.log(`✅ 规则已激活: ${rule.name}`);
        }
    }

    // 停用规则
    deactivateRule(ruleId) {
        const rule = this.rules.find(r => r.id === ruleId);
        if (rule) {
            rule.active = false;
            console.log(`⏸️ 规则已停用: ${rule.name}`);
        }
    }

    // 删除规则
    removeRule(ruleId) {
        const index = this.rules.findIndex(r => r.id === ruleId);
        if (index !== -1) {
            const rule = this.rules[index];
            this.rules.splice(index, 1);
            console.log(`🗑️ 规则已删除: ${rule.name}`);
        }
    }
}

module.exports = new RuleEngine();
